package com.example.ai.test;

import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.*;
import org.apache.poi.util.Units;
import org.springframework.core.io.ClassPathResource;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class WordPageSplitter {

    public static List<String> splitWordDocumentByPages(String filePath) throws IOException {
        List<String> pages = new ArrayList<>();
        try (FileInputStream fis = new FileInputStream(filePath);
             XWPFDocument document = new XWPFDocument(fis)) {

            List<XWPFParagraph> paragraphs = document.getParagraphs();
            StringBuilder currentPage = new StringBuilder();
            int currentPageHeight = 0;
            int pageHeight = 11 * Units.toEMU(72); // Example page height in EMU (English Metric Units)

            for (XWPFParagraph paragraph : paragraphs) {
                currentPage.append(paragraph.getText()).append("\n");
                currentPageHeight += estimateParagraphHeight(paragraph.getText());

                if (currentPageHeight >= pageHeight) {
                    pages.add(currentPage.toString());
                    currentPage.setLength(0);
                    currentPageHeight = 0;
                }
            }

            if (currentPage.length() > 0) {
                pages.add(currentPage.toString());
            }
        }
        return pages;
    }

    private static int estimateParagraphHeight(String paragraph) {
        // Simple estimation based on average line height
        return 14 * Units.toEMU(1); // Example line height in EMU
    }

    public static void main(String[] args) {
        try {
            ClassPathResource resource = new ClassPathResource("data/浙江省劳动人事争议仲裁申请书V1.1.docx");
            List<String> pages = splitWordDocumentByPages(resource.getFile().getAbsolutePath());
            for (int i = 0; i < pages.size(); i++) {
                System.out.println("Page " + (i + 1) + ":\n" + pages.get(i));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}